package com.rs.admin.sys.org.service.impl;

import com.baomidou.mybatisplus.plugins.pagination.PageHelper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.rs.admin.sys.org.entity.Department;
import com.rs.admin.sys.org.entity.User;
import com.rs.admin.sys.org.entity.UserDepartment;
import com.rs.admin.sys.org.entity.UserDetail;
import com.rs.admin.sys.org.mapper.UserDetailMapper;
import com.rs.admin.sys.org.mapper.UserMapper;
import com.rs.admin.sys.org.service.UserService;
import com.rs.admin.sys.org.vo.UserVo;
import com.rs.common.entity.PageParams;
import com.rs.common.exception.RRException;
import com.rs.common.page.PageResult;
import com.rs.common.page.PageUtils;

import com.rs.common.utils.BCrypt.BCryptUtil;
import com.rs.common.utils.constant.Constant;
import com.rs.common.utils.result.R;
import com.rs.common.validator.Assert;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author hedonglin
 * @since 2017-12-20
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Autowired
    private UserMapper userMapper;

    /**
     * 根据唯一性字段查询用户信息，账号，电话，邮箱等
     * @param uniqKey
     * @return
     */

    @Override
    public User findUserByUniqKey(String uniqKey) {
        //账号
        String USER_ACCOUNT = Constant.LoginType.USER_ACCOUNT.getValue();
        //手机号
        String USER_MOBILE = Constant.LoginType.USER_MOBILE.getValue();
        //邮箱
        String USER_EMAIL = Constant.LoginType.USER_EMAIL.getValue();

        HashMap<String, Object> map = new HashMap<>();
        List<User> users = new ArrayList<>();
        User user = new User();

        //根据账号查询
        map.put(USER_ACCOUNT,uniqKey);
        user = getListFirst(map,users);
        if (user!=null) return user;

        //根据手机号查询，删除旧key，加入新的
        map.remove(USER_ACCOUNT);
        map.put(USER_MOBILE,uniqKey);
        user = getListFirst(map,users);
        if (user!=null) return user;

        //根据邮箱查询，删除旧key，加入新的
        map.remove(USER_MOBILE);
        map.put(USER_EMAIL,uniqKey);
        user = getListFirst(map,users);

        return user;
    }

    /**
     * 分页查询用户
     * @param params
     * @return
     */
    @Override
    public PageResult findList(PageParams params) {
        //开启分页
        PageHelper.startPage(params.getPageNum()-1,params.getPageSize());

        //自定义查询
        List<UserVo> list = userMapper.findByCondition(params);

        //设置部门名称数组
        for (UserVo userVo:list) {
            if (userVo.getDepts().size()>0){
                String[] deptNames = new String[userVo.getDepts().size()];
                List<Department> depts = userVo.getDepts();
                for (int i = 0; i < depts.size(); i++) {
                    Department department = userVo.getDepts().get(i);
                    if (department==null) continue;
                    if (StringUtils.isBlank(department.getJcTitle())){
                        deptNames[i]="";
                    }else {
                        deptNames[i]=department.getJcTitle();
                    }
                }
                userVo.setDeptNames(deptNames);
            }
        }

        PageResult pageResult = PageUtils.builder().pageHelperToPage(PageHelper.getPagination(), list);
        return pageResult;
    }

    /**
     * 新增用户以及用户详情，不选择部门
     * @param user
     * @return
     */
    @Override
    public boolean add(UserVo user) {
        //密码不为空则加密
        if (StringUtils.isNotBlank(user.getPassword())){
            user.setPassword(BCryptUtil.createPwdHash(user.getPassword()));
        }
        //设置默认状态为正常
        if (user.getStatus()==null && user.getStatus()<0){
            user.setStatus(Constant.BaseStatus.NORMAL.getValue());
        }
        //属性复制
        User baseUser = new User();
        BeanUtils.copyProperties(user,baseUser);

        boolean b = this.insertAllColumn(baseUser);
        if (b){
            //返回主键
            user.setId(baseUser.getId());
            //详情
            UserDetail userDetail = new UserDetail();
            if(baseUser.getId()>0){
                //获取用户新增成功的id、
                Long userId = baseUser.getId();
                //设置用户id,这里使用activeRecord
                userDetail.setUserId(userId);
                if(user.getDetail()==null){
                    //只插入id
                   b =  userDetail.insert();
                }else{
                    //插入扩展信息
                    userDetail = user.getDetail();
                    //重新设置用户id
                    userDetail.setUserId(userId);
                    b =  userDetail.insert();
                }
                user.setDetail(userDetail);
            }
        }
        return b;
    }

    /**
     * 修改用户
     * @param user
     * @return
     */
    @Override
    public boolean update(UserVo user) {
        if (user.getId()==null){
            Assert.isNull(user.getId()+"","用户id不能为空");
        }

        //密码不为空则加密
        if (StringUtils.isNotBlank(user.getPassword())){
            user.setPassword(BCryptUtil.createPwdHash(user.getPassword()));
        }
        //设置默认状态为正常
        if (user.getStatus()==null && user.getStatus()<0){
            user.setStatus(Constant.BaseStatus.NORMAL.getValue());
        }

        //更新时间
        Date data = new Date();
        user.setUpdateTime(data);

        //属性复制
        User baseUser = new User();
        BeanUtils.copyProperties(user,baseUser);
        //更新基本信息
        boolean b = this.updateById(user);

        if (b){
            //返回主键
            user.setId(baseUser.getId());
            //详情
            UserDetail userDetail = new UserDetail();
            if(baseUser.getId()>0){
                //获取用户新增成功的id、
                Long userId = baseUser.getId();
                //设置用户id,这里使用activeRecord
                userDetail.setUserId(userId);
                if(user.getDetail()!=null){
                    userDetail = user.getDetail();
                    //新增或者修改
                    b = userDetail.insertOrUpdate();
                    user.setDetail(userDetail);
                }
            }
        }
        return b;
    }

    




    /**
     * 根据map查询用户并返回第一条数据
     * @param map
     * @param users
     * @return
     */
    private User getListFirst(Map<String,Object> map, List<User> users){
        users = userMapper.selectByMap(map);
        if (users.size() > 0){
            return users.get(0);
        }
        return null;
    }
}
